package com.czk.zookeeper.zookeepercli.globallyUniquedid;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * 分布式全局唯一id
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/5 21:30
 */
public class GloballyUniqueId implements Watcher {
    /**
     * 计数器对象
     */
    static CountDownLatch countDownLatch = new CountDownLatch(1);
    /**
     * 连接对象
     */
    static ZooKeeper zooKeeper;

    /**
     * 生成序号的节点
     */
    public String nodePath = "/uniqueId";

    @Override
    public void process(WatchedEvent watchedEvent) {
        try {
            // 捕获事件类型
            if (watchedEvent.getType() == Event.EventType.None) {
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                    //
                    System.out.println("连接成功");
                    // 计数器减一
                    countDownLatch.countDown();
                }
                if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                    System.out.println("断开连接");
                }
                if (watchedEvent.getState() == Event.KeeperState.Expired) {
                    System.out.println("会话超时");
                }
                if (watchedEvent.getState() == Event.KeeperState.AuthFailed) {
                    System.out.println("认证失败");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public GloballyUniqueId() {
        try {
            zooKeeper = new ZooKeeper("192.168.25.133:2181", 10000, this);
            // 阻塞线程，等待连接创建成功
            countDownLatch.await();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取分布式的唯一id
     *
     * @return
     */
    public String getUniqueId() {
        try {
            // 创建临时有序节点->seesion过期后失效
            String path = zooKeeper.create(nodePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            // 将节点进行截取
            return path.substring(9);
        } catch (Exception ex) {

        }
        return null;
    }

    public static void main(String[] args) {
        // 创建对象
        GloballyUniqueId uniqueId = new GloballyUniqueId();
        for (int i = 0; i < 5; i++) {
            String id = uniqueId.getUniqueId();
            System.out.println(id);
        }

    }
}
